package com.wu.http.server;

import com.wu.javax.servlet.ServletResponse;
import com.wu.javax.servlet.http.Cookie;
import com.wu.javax.servlet.http.HttpServletResponse;

import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * @program: tomcatServer
 * @author: 吴磊
 * @create: 2021-12-31 14:57
 */
public class MyWriter extends PrintWriter {
    private ServletResponse response;

    public MyWriter(OutputStream out) {
        super(out);
    }

    public MyWriter(OutputStream out, ServletResponse response) {
        super(out);
        this.response = response;
    }

    @Override
    public void println(String content) {
        this.println(content, null);
    }

    public void println(String content, String contentType) {
        if (contentType == null) {
            contentType = "application/json";
        }
        long length = content.length();
        StringBuffer sb = new StringBuffer();
        String protocol200 = "HTTP/1.0 200 OK\r\nContent-Type: " + contentType + "\r\nContent-Length: "
                + length + "\r\n";
        sb.append(protocol200);

        //拼接Cookie
        Cookie[] cookies = ((HttpServletResponse) this.response).getCookies();
        if (cookies != null && cookies.length > 0) {
            sb.append("Set-Cookie: ");
            for (Cookie cookie : cookies) {
                sb.append(cookie);
            }
        }
        sb.append("\r\n\r\n");
        sb.append(content);
        super.println(sb);
        super.flush();
    }

}
